package com.denghq.projectbuilder.component.msgbus.autoconfigure.rabbitmq;

import com.denghq.projectbuilder.component.msgbus.annotation.RabbitMsgBusProcessor;
import com.denghq.projectbuilder.component.msgbus.bus.IMsgProcessor;
import com.denghq.projectbuilder.component.msgbus.bus.impl.RabbitMqMsgBus;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 订阅构建器
 */
public class MsgBusSubscribeBuilder {

    private final RabbitMqMsgBus msgBus;
    private final List<IMsgProcessor> msgProcessors;

    public MsgBusSubscribeBuilder(RabbitMqMsgBus msgBus, List<IMsgProcessor> msgProcessors) {
        this.msgBus = msgBus;
        this.msgProcessors = msgProcessors;
    }

    @PostConstruct
    public void build() {
        if (!CollectionUtils.isEmpty(msgProcessors)) {
            msgProcessors.forEach(msgProcessor -> {
                RabbitMsgBusProcessor ann = AnnotationUtils.findAnnotation(msgProcessor.getClass(), RabbitMsgBusProcessor.class);
                if (ann != null) {
                    Assert.hasText(ann.topic(), "未获取到topic,class：" + msgProcessor.getClass());
                }
                this.msgBus.subscribe(ann.topic(), msgProcessor);
            });
        }
    }

}
